﻿package ygg.encoding.swf
{
	import ygg.binary.IContext;
	import j.sus2maj7.encoding.*;
	
	public class SwfContext implements IContext
	{
		
		private var _stringRT:Array;
		private var _complexRT:Array; //Objects, typed Objects, Arrays, Dates, XMLDocument, XML, and ByteArrays)
		private var _traitsRT:Array;
		
		private var _nameCodec:ICodec;
		private var _codecFactory:ICodecFactory;
		
		private var _version:uint;
		
		public function SwfContext()
		{
			_stringRT = [];
			_complexRT = [];
			_traitsRT = [];
		}
		
		public function addString(s:String):void
		{
			if (s.length > 0)
			{
				_stringRT[_stringRT.length] = s;
			}
		}
		
		public function addComplex(c:Object):void
		{
			trace('adding complex', c);
			_complexRT[_complexRT.length] = c;
		}
		
		public function addTraits(t:Object):void
		{
			_traitsRT[_traitsRT.length] = t;
		}
		public function getString(i:int):String
		{
			return _stringRT[i];
		}
		
		public function getComplex(i:int):Object
		{
			return _complexRT[i];
		}
		
		public function getTraits(i:int):Object
		{
			return _traitsRT[i];
		}
		
		public function indexOfString(s:String):int
		{
			//loop through
			var len:int = _stringRT.length;
			
			var retVal:int = -1;
			
			while (len--)
			{
				if (s == _stringRT[len])
				{
					retVal = len;
					break;
				}
			}
			
			return retVal;
		}
		
		public function indexOfComplex(o:Object):int
		{
			var len:int = _complexRT.length;
			
			var retVal:int = -1;
			
			trace('complex len=', len);
			while (len--)
			{
				if (o == _complexRT[len])
				{
					retVal = len;
					break;
				}
			}
			
			return retVal;
		}
		
		public function indexOfTraits(t:Object):int
		{
			var len:int = _traitsRT.length;
			
			var retVal:int = -1;
			var o:Object;
			
			while (len--)
			{
				o = _traitsRT[len];
				
				if (t.alias == o.alias)
				{
					trace("SAME TYPE TRAIT");
					if (haveSameProps(o, t) )
					{
						retVal = len;
						break;
					}
				}
			}
			
			return retVal;
		}
		private function haveSameProps(o1:Object, o2:Object):Boolean
		{
			var bool:Boolean = true;
			
			for (var p:* in o1.props)
			{
				if ( o2[p] == p)
				{
					bool = false;
					break;
				}
			}
			
			return bool;
		}
		
		public function get codecFactory():ICodecFactory { return _codecFactory; }
		
		public function set codecFactory(value:ICodecFactory):void
		{
			_codecFactory = value;
		}
		
		public function get nameCodec():ICodec { return _nameCodec; }
		
		public function set nameCodec(value:ICodec):void
		{
			_nameCodec = value;
		}
		
		public function get version():uint { return _version; }
		
		public function set version(value:uint):void
		{
			_version = value;
		}
	}
}